'''
Created on 06/gen/2013

@author: Arletti Luca,Spina Andrea
'''

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import cv


def GrabCut ():
    
    im = cv2.imread(INPUT_IMAGE)
    cv2.imshow('Image',im) 
    cv2.waitKey(1000)
    
    h,w = im.shape[:2]
    print 'Original Size Image',h,w
    mask = np.zeros((h,w),dtype='uint8')
    
    
    rect = (5,5,w-10,h-10)
    tmp1 = np.zeros((1, 13 * 5))
    tmp2 = np.zeros((1, 13 * 5))
    
    cv2.grabCut(im,mask,rect,tmp1,tmp2,5,mode=cv2.GC_INIT_WITH_RECT)
    #cv2.imwrite ('mask1.png',mask)
    
    h_plt=h/10
    w_plt=w/10
    
    fig=plt.figure(figsize=(w_plt,h_plt))
    ax = plt.axes([0.0, 0.0, 1.0, 1.0]) 
    ax.set_xticks([]) 
    ax.set_yticks([])  
    plt.imshow(mask)
    fig.savefig(GRABCUT_MASK, dpi=10)
    print 'GrabCut Process [OK]' 
    
def Threshed_Mask():
    img = cv2.imread(GRABCUT_MASK)
    
    cv2.imshow('GrabCut Mask',img) 
    cv2.waitKey(1000)
    
    GRABCUT_RED = np.array([0,0, 127],np.uint8)
    
    #hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    
    #cv2.imshow('HSV Color Mask',hsv_img) 
    #cv2.waitKey(1000)
    
    frame_threshed = cv2.inRange(img,GRABCUT_RED,GRABCUT_RED)
    cv2.imwrite(THRESHED_MASK, frame_threshed)
    
    
    print 'Masking Process [OK]'
    
def BoundingRect():
    frame_threshed = cv2.imread(THRESHED_MASK)
    
    cv2.imshow('White-Black Mask',frame_threshed) 
    cv2.waitKey(1000)
    
    original_img=cv2.imread(INPUT_IMAGE)
    #cv2.imshow('Bounding Rect',im) 
    #cv2.waitKey(1000)
    
    imgray = cv2.cvtColor(frame_threshed,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,127,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    
    #Number of object find in the image
    print 'Number of objects detected:',len(contours)
    
    count_obj=0
    #For all contours 
    for cnt in contours:
                    count_obj+=1
                    #It's possible ignore objects with small areas 
                    area = cv2.contourArea(cnt)
                    print 'Object ',count_obj,'Area ',area
                    # Draw rectangles
                    x,y,w,h = cv2.boundingRect(cnt)
                    GetSubRect(count_obj,x,y,h,w)
                    cv2.rectangle(original_img,(x,y),(x+w,y+h),(0,255,0),2)
                    cv2.rectangle(frame_threshed,(x,y),(x+w,y+h),(0,255,0),2)
                    
    cv2.imshow('Bounding Rect Mask',frame_threshed) 
    cv2.waitKey(1000)
    
    cv2.imshow('Bounding Rect Original Image',original_img) 
    cv2.waitKey(1000)
    
    cv2.imwrite(BOUNDING_RECT_IMAGE,original_img)
    
    print 'BoundingRect Extraction [OK]'
    
    
def GetSubRect(count,x,y,h,w):
    cvIm = cv.LoadImage(INPUT_IMAGE)
    #cv.Rectangle(cvIm,(x,y),(x+w,y+h),(0,255,0),2)
    #cv.ShowImage('Test SubRect',cvIm)
    #cv.WaitKey(1000)
    cropped = cv.CreateImage((w,h), cvIm.depth, cvIm.nChannels)
    src_region = cv.GetSubRect(cvIm,(x,y,w,h))
    cv.Copy(src_region, cropped)
    cv.SaveImage('crop'+str(count)+'.jpg',cropped)
    print 'crop',str(count),'.jpg SAVED'        
      
    
'''
MAIN
'''      
        
INPUT_IMAGE = 'grabcut-sample.jpg'
GRABCUT_MASK='grabcut_mask.png'
THRESHED_MASK='threshed_mask.jpg'
BOUNDING_RECT_IMAGE='bounding_rect_image.jpg'
TIMESHOW=1000



#Process Image with Grabcut
GrabCut()
#Create a white-black mask                
Threshed_Mask()
#Find Contours,BoundingRect and GetSubRect
BoundingRect()

print 'Process Complete Successfully [OK]'
print 'Debug Files:',GRABCUT_MASK,THRESHED_MASK,BOUNDING_RECT_IMAGE

'''
END
'''


